package com.app.business.service;

import com.app.business.model.ActionHistory;
import com.app.business.model.Contract;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.jpa.PageBean;
import com.app.system.jpa.Wrapper;
import com.app.system.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  操作记录历史
 * Created by ddz on 2020/12/8.
 */
@Service
public class ActionHistoryService extends JpaBaseDao<ActionHistory, Integer> {

    @Autowired
    private ContractService contractService;

    /**
     * 根据协议Id得到操作记录
     *
     * @param contractId
     * @return
     */
    public List<ActionHistory> getActionHistoryListByContractId(Integer contractId) {
        //查询语句
        String hql = " from ActionHistory ah where ah.contract.id = :contractId order by ah.doDate desc";
        Map<String, Object> map = new HashMap<>();
        map.put("contractId", contractId);
        return this.findHql(hql, map);
    }

    /**
     * 交房列表//所分配权限内档案已发放房源
     *
     * @return
     */
    public PageBean<ActionHistory> getActionHistoryPageBean(Integer contractId) {

        //查询语句
        StringBuffer query = new StringBuffer("ah from ActionHistory ah inner join fetch ah.contract c inner join fetch c.zsProject zsp  ");

        StringBuffer orderBy = new StringBuffer("ah.doDate");
        Wrapper wrapper = new Wrapper(query, orderBy);
        wrapper.initSearchParams();
        wrapper.andEq("c.id", contractId);
        return this.pageHql(wrapper);
    }


    /**
     *
     * @param contractId
     * @param operation
     */
    @Transactional
    public void saveActionHistoryByContractId(Integer contractId,String operation,String doType) {
        //得到操作人
        String doName = WebUtils.getLoginUserInfo().getName();
        Contract contract=this.contractService.findOne(contractId);
        //保存操作记录
        ActionHistory actionHistory = new ActionHistory();
        actionHistory.setDoName(doName);
        actionHistory.setDoDate(new Date());
        actionHistory.setOperation(operation);
        actionHistory.setDoType(doType);
        actionHistory.setContract(contract);
        this.save(actionHistory);
    }
}